#include "opencv2/opencv.hpp"
#include <string>
#include <math.h>
#include <dirent.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fstream>

#include <opencv2/opencv.hpp>

#include "palmdll_yjy.h"

using namespace std;

cv::Mat adjustRotation(cv::Mat &img)
{
    auto debug = [](cv::Mat &img) -> void {
        cv::imshow("img", img);
        cv::waitKey();
    };

    cv::Mat img2, adjusted;
    cv::Point2d rotateCenter(img.cols / 2, img.rows / 2);
    cv::cvtColor(img, img2, CV_BGR2GRAY);
    cv::threshold(img2, img2, 28, 255, cv::THRESH_BINARY);
    //debug(img2);

    double theta = getRotationBias(img2);
    cout << "theta degree = " << theta << endl;
    const double scaleRate = 1.0;
    //角度制
    cv::Mat rotateMatrix = cv::getRotationMatrix2D(rotateCenter, theta, scaleRate);
    cv::warpAffine(img, adjusted, rotateMatrix, img.size());
    //debug(adjusted);

    return adjusted;
}

/*
this application estimate rotation of images and adjust them;
the results are outputed to `img_save_path`
 */
int main(int args, char **argv)
{
    const string img_load_path = "/home/yjy/dataset/palmprint_dectection_tongji/LHand/palmprint_HITsz_format/";
    const string img_save_path = "/home/yjy/dataset/palmprint_dectection_tongji/LHand/palmprint_rotation_adjusted/";
    string file_name;
    dirent *filename;
    DIR *dir = opendir(img_load_path.c_str());

    while ((filename = readdir(dir)) != NULL)
    {
        if (strcmp(filename->d_name, ".") == 0 ||
            strcmp(filename->d_name, "..") == 0)
            continue;

        file_name = filename->d_name;
        cout << "handling " << file_name << endl;
        cv::Mat img = cv::imread(img_load_path + file_name);
        cv::Mat adjusted = adjustRotation(img);
        cv::imwrite(img_save_path + file_name, adjusted);
    }

    return 0;
}